﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports ISNet.WebUI.WebTreeView
Imports log4net

Partial Class Sinchuatobtan
    Inherits System.Web.UI.Page
    Public price As String = ""
    Public CodeTxt As String = ""
    Public FCTR1 As String = ""
    Public price2 As String = ""
    Public CodeTxt2 As String = ""
    Public FCTR2 As String = ""
    Public price3 As String = ""
    Public CodeTxt3 As String = ""
    Public FCTR3 As String
    Public price4 As String = ""
    Public CodeTxt4 As String = ""
    Public price5 As String = ""
    Public CodeTxt5 As String = ""
    Public Max1 As String = ""
    Public Max2 As String = ""
    Public Max3 As String = ""
    Public dfctr As String

    Dim lockhash As New Hashtable
    Private Shared logger As ILog = LogManager.GetLogger("Sinchuatobtan")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub

    Sub setDefault()
        If Session("dfctr") IsNot Nothing Then
            dfctr = "dfc= '" & Session("dfctr") & "'; dfcname = '" & Session("dfctrname") & "';"
        Else
            dfctr = "dfc = 'null'"
        End If
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'cmmtcode = Session("CMMT_OT_CODE")
        PlanYearsTxt.Text = Session("PlanYear")
        VersionTxt.Text = Session("Versions")
        If Session("FCTR") Is Nothing Then
            Response.Redirect("Selector.aspx?type=12")
        End If
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        GenerateValues()
        setDefault()
        If IsPostBack = False Then
            Session.Remove("Search")
            Session.Remove("search_fctr")

            Label1.Text = "ระบบจัดทำงบประมาณ >> จัดทำงบประมาณ >> ผลิตภัณฑ์สินเชื่อ >> ค่าตอบแทนสินเชื่อ"
            'If Session("Versions") = 1 Then
            '    div1.Visible = False
            '    div2.Visible = False
            '    SearhBtn.Visible = False
            '    WebTreeView1.Visible = False
            '    WebTreeView2.Visible = False
            '    WebTreeView3.Visible = False
            'End If
            Dim adapter As New SplitBudgetDSTableAdapters.ProductsTableAdapter

            Dim data As New SplitBudgetDS.ProductsDataTable
            'data = adapter.GetDataByPlanYear(Val(Session("PlanYear")))

            data = adapter.GetDataByF06(PlanYearsTxt.Text)
            ms8.DataValueField = "ProductCode"
            ms8.DataTextField = "Description"
            ms8.DataSource = data
            ms8.DataBind()

        End If


        If WebGrid1.IsFlyPostBack = False Then

            Dim adap13 As New MSinchuaTableAdapters.SumP13TableAdapter
            Dim adap22 As New MSinchuaTableAdapters.SumP22TableAdapter
            Dim adap25 As New MSinchuaTableAdapters.SumP25TableAdapter
            Dim adapcal As New MSinchuaTableAdapters.ProductComCalTableAdapter

            Dim dt13 As New MSinchua.SumP13DataTable
            Dim dt22 As New MSinchua.SumP22DataTable
            Dim dt25 As New MSinchua.SumP25DataTable
            Dim dtcal As New MSinchua.ProductComCalDataTable

            dt13 = adap13.GetData(Val(PlanYearsTxt.Text), VersionTxt.Text)
            dt22 = adap22.GetData(Val(PlanYearsTxt.Text), VersionTxt.Text)
            dt25 = adap25.GetData(Val(PlanYearsTxt.Text), VersionTxt.Text)
            dtcal = adapcal.GetData(Val(PlanYearsTxt.Text))


            Dim i As Integer = 0
            Dim j As Integer = 0
            Dim k As Integer = 0
            Dim l As Integer = 0
            'cmt_hash.Clear()

            For Each row As MSinchua.SumP13Row In dt13
                CodeTxt += "CodeArray[" & i & "] = new Array('" & row.Product_ProductCode & "','" & row.FundCenter_FundcenterCode & "');"
                'FCTR1 += "CodeArray[" & i & "][1]='" & row.FundCenter_FundcenterCode & "';"
                If row.IsSumP13Null Then
                    price += "Price[" & i & "]='" & "0" & "';"
                Else
                    price += "Price[" & i & "]='" & row.SumP13 & "';"
                End If
                i += 1

            Next
            Max1 = "max1 = " & i & ";"
            For Each row2 As MSinchua.SumP22Row In dt22
                CodeTxt2 += "CodeArray2[" & j & "] = new Array('" & row2.Product_ProductCode & "','" & row2.FundCenter_FundcenterCode & "');"
                'FCTR2 += "CodeArray2[" & j & "][1]='" & row2.FundCenter_FundcenterCode & "';"
                If row2.IsSumP22Null Then
                    price2 += "Price2[" & j & "]='" & "0" & "';"
                Else
                    price2 += "Price2[" & j & "]='" & row2.SumP22 & "';"
                End If
                j += 1
            Next
            Max2 = "max2 = " & j & ";"
            For Each row3 As MSinchua.SumP25Row In dt25
                CodeTxt3 += "CodeArray3[" & k & "] = new Array('" & row3.Product_ProductCode & "','" & row3.FundCenter_FundcenterCode & "');"
                ' FCTR3 += "CodeArray3[" & k & "][1]='" & row3.FundCenter_FundcenterCode & "';"
                If row3.IsSumP25Null Then
                    price3 += "Price3[" & k & "]='" & "0" & "';"
                Else
                    price3 += "Price3[" & k & "]='" & row3.SumP25 & "';"
                End If
                k += 1
            Next
            Max3 = "max3 = " & k & ";"
            For Each row4 As MSinchua.ProductComCalRow In dtcal
                CodeTxt4 += "CodeArray4[" & l & "]='" & row4.ProductCode & "';"
                If row4.IsCompensateRateNull Then
                    price4 += "Price4[" & l & "]='" & "0" & "';"
                Else
                    price4 += "Price4[" & l & "]='" & row4.CompensateRate & "';"
                End If
                CodeTxt5 += "CodeArray5[" & l & "]='" & row4.ProductCode & "';"
                If row4.IsCalculationTypeNull Then
                    price5 += "Price5[" & l & "]='" & "0" & "';"
                Else
                    price5 += "Price5[" & l & "]='" & row4.CalculationType & "';"
                End If
                l += 1
            Next

            'PlotNode()
        End If


        Dim prefil2 As String = ""
        prefil2 = Session("prefilter")
        Dim re_adap As New FormLockDSTableAdapters.FundCenterReleasesTableAdapter
        Dim rsql As String = ""
        rsql = " SELECT FundCenterReleases.FundCenter_FundCenterCode FROM FundCenterReleases "
        rsql += " WHERE PlanYear = " & Val(PlanYearsTxt.Text) & " "
        rsql += " AND Version = '" & VersionTxt.Text & "' "
        rsql += " AND FundCenter_FundCenterCode IN (" & prefil2 & ")" : rsql += " AND ReleaseFlag = 'Y' "
        'Response.Write(rsql)
        'Exit Sub
        Dim re_dt As New FormLockDS.FundCenterReleasesDataTable
        re_adap.GetDataByFilter(re_dt, rsql)
        For Each ritem As FormLockDS.FundCenterReleasesRow In re_dt
            lockhash.Remove(ritem.FundCenter_FundCenterCode) : lockhash.Add(ritem.FundCenter_FundCenterCode, True)
        Next

    End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        Dim adapter As New MSinchuaTableAdapters.SinchuaValueTableAdapter
        Dim datatable As New MSinchua.SinchuaValueDataTable
        Dim prefil As String = ""
        prefil = Session("prefilter")
        WebGrid1.RootTable.ColumnSets.GetNamedItem("ColumnSet4").Caption = "สินเชื่อปี " & Val(PlanYearsTxt.Text) - 1
        WebGrid1.RootTable.ColumnSets.GetNamedItem("ColumnSet0").Caption = "สินเชื่อปี " & Val(PlanYearsTxt.Text)
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim sql As String = ""
            sql = "  SELECT BudgetDetails.Id, BudgetDetails.PlanYear, BaseYear, [Version], Element1, Element2, Element3, Element4,Element5,Amount, BudgetDetails.FormId, Note, "
            sql += " BudgetDetails.Product_ProductCode AS ProductCode, BudgetDetails.FundCenter_FundCenterCode, "
            sql += " BudgetDetails.Cmmt_CmmtCode, CmmtDetail_Id, Attachments_amount, Products.[Description] AS ProductDesc, "
            sql += " FundCenters.Description AS FundCenterName,"
            sql += " BudgetDetails.ProductItemNo as ProItemID , Products.CompensateRate, BudgetDetails.Note "
            sql += " , Products.CalculationType "
            sql += " , (Select Description from ProductItems where FormId='F06' and ItemNo = BudgetDetails.ProductItemNo and PlanYear = '" & Val(PlanYearsTxt.Text) & "') As ProItemDesc"
            sql += " , 1 AS SumAmountX"
            sql += " FROM BudgetDetails INNER JOIN Products ON BudgetDetails.Product_ProductCode = Products.ProductCode "
            sql += " INNER JOIN FundCenters ON BudgetDetails.FundCenter_FundCenterCode = FundCenters .FundCenterCode "
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            If TabContainer1.ActiveTab.ID = TabPanel1.ID Then

                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value

                If hdf1.Value.ToString <> "" Then
                    sql += " AND BudgetDetails.Product_ProductCode IN ("
                    Dim Numx As Array = hdf1.Value.Split(",")
                    For i = 0 To Numx.Length - 1
                        If Val(Numx(i)) <> 0 Then
                            If i <> 0 Then
                                sql += ","
                            End If
                            sql += Numx(i).ToString
                        End If

                    Next
                    sql += ") "
                End If
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " AND Products.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " AND FundCenters.PlanYear = " & PlanYearsTxt.Text & " "

                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                sql += " AND BudgetDetails.FormId = 'F06' "
                sql += " AND BudgetDetails.Product_ProductCode IS NOT NULL "
                If fctr <> "" Then
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                End If

                adapter.GetDataByFilter(datatable, sql)

            ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then

                'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode IN (SELECT FundCenter_FundCenterCode FROM FundCenterHierarchies "
                'sql += " WHERE FundCenter_FundCenterCode = " & Val(WebCombo3.Value) & " OR ParentFundCenterHierarchy_Id = " & Val(WebCombo3.Value) & ") "
                If hdf1.Value.ToString <> "" Then
                    sql += " AND BudgetDetails.Product_ProductCode IN ("
                    Dim Numx As Array = hdf1.Value.Split(",")
                    For i = 0 To Numx.Length - 1
                        If Val(Numx(i)) <> 0 Then
                            If i <> 0 Then
                                sql += ","
                            End If
                            sql += Numx(i).ToString
                        End If

                    Next
                    sql += ") "
                End If
                sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " AND Products.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " AND FundCenters.PlanYear = " & PlanYearsTxt.Text & " "
                sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"
                sql += " AND BudgetDetails.FormId = 'F06' "
                sql += " AND BudgetDetails.Product_ProductCode IS NOT NULL "
                If fctr <> "" Then
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                End If



                adapter.GetDataByFilter(datatable, sql)
                '  Response.Write(sql)

            End If

            'Response.Write(sql)




            datatable.Columns("PlanYear").AllowDBNull = True
            datatable.Columns("BaseYear").AllowDBNull = True
            datatable.Columns("Version").AllowDBNull = True
            datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
            datatable.Columns("ProItemID").AllowDBNull = True
            datatable.Columns("SumAmountX").AllowDBNull = True
            datatable.Columns("SumAmountX").ReadOnly = False
            datatable.Columns("Id").ReadOnly = False

            'Response.Write(Val(Session("FCTR")))

            e.DataSource = datatable


            'datatable = adapter.GetDataByMultiple(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))
        Else
            Dim sql As String = ""
            Dim fctr As String = ""
            fctr = Session("search_fctr")

            sql = "  SELECT BudgetDetails.Id, BudgetDetails.PlanYear, BaseYear, [Version], Element1, Element2, Element3, Element4,Element5,Amount, BudgetDetails.FormId, Note, "
            sql += " BudgetDetails.Product_ProductCode AS ProductCode, BudgetDetails.FundCenter_FundCenterCode, "
            sql += " BudgetDetails.Cmmt_CmmtCode, CmmtDetail_Id, Attachments_amount, Products.[Description] AS ProductDesc, "
            sql += " FundCenters.Description AS FundCenterName,"
            sql += " BudgetDetails.ProductItemNo as ProItemID , Products.CompensateRate, BudgetDetails.Note "
            sql += " , Products.CalculationType "
            sql += " , (Select Description from ProductItems where FormId='F06' and ItemNo = BudgetDetails.ProductItemNo and PlanYear = '" & Val(PlanYearsTxt.Text) & "') As ProItemDesc"
            sql += " , 1 AS SumAmountX"
            sql += " FROM BudgetDetails INNER JOIN Products ON BudgetDetails.Product_ProductCode = Products.ProductCode "
            sql += " INNER JOIN FundCenters ON BudgetDetails.FundCenter_FundCenterCode = FundCenters .FundCenterCode "
            sql += " Where 1=1 "
            sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"

            sql += " AND BudgetDetails.FormId = 'F06' "


            prefil = Session("prefilter")

            '    sql += " WHERE 1 = 1 "
            '    'sql += " WHERE BudgetDetails.FundCenter_FundCenterCode BETWEEN " & Val(WebCombo1.Value) & " AND " & Val(WebCombo2.Value)
            '    sql += " AND Version = " & Val(VersionTxt.Text)
            '    sql += " AND FormId = 'F01' "
            '    sql += " AND BudgetDetails.Project_ProjectCode IS NOT NULL "
            If fctr <> "" Then
                If fctr <> "0" Then
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
                Else
                    sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
                End If
            Else
                sql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
            End If
            sql += " AND BudgetDetails.PlanYear = " & PlanYearsTxt.Text & " "
            sql += " AND Products.PlanYear = " & PlanYearsTxt.Text & " "
            sql += " AND FundCenters.PlanYear = " & PlanYearsTxt.Text & " "
            sql += " AND BudgetDetails.Version = '" & VersionTxt.Text & "'"

            adapter.GetDataByFilter(datatable, sql)
            ' MsgBox(datatable.Count)
            ' Response.Write(sql)
            'datatable = adapter.GetDataByMultiple2(Val(Session("PlanYear")), Val(Session("Versions")), Session("users"))


            datatable.Columns("PlanYear").AllowDBNull = True
            datatable.Columns("BaseYear").AllowDBNull = True
            datatable.Columns("Version").AllowDBNull = True
            datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
            datatable.Columns("ProItemID").AllowDBNull = True
            datatable.Columns("SumAmountX").AllowDBNull = True
            datatable.Columns("SumAmountX").ReadOnly = False
            datatable.Columns("Id").ReadOnly = False
            'Response.Write(Val(Session("FCTR")))
            e.DataSource = datatable

        End If

        'Else
        '    Dim sql As String = ""

        '    sql += " ORDER BY FundCenter_FundCenterCode,Id"
        '    adapter.GetDataByFilter(datatable, sql)

        '    'datatable = adapter.GetDataBySingle(Val(Session("PlanYear")), Val(Session("Versions")), Val(Session("FCTR")))

        '    datatable.Columns("PlanYear").AllowDBNull = True
        '    datatable.Columns("BaseYear").AllowDBNull = True
        '    datatable.Columns("Version").AllowDBNull = True
        '    datatable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
        '    'datatable.Columns("FundCenter_PlanYear").AllowDBNull = True
        '    'datatable.Columns("Fund_FundCode").AllowDBNull = True
        '    'datatable.Columns("Fund_PlanYear").AllowDBNull = True

        '    datatable.Columns("Id").ReadOnly = False

        '    'Response.Write(Val(Session("FCTR")))
        '    e.DataSource = datatable
        'End If

    End Sub
    Dim old_fctr As String = ""
    Dim old_prod As String = ""
    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)

        e.Row.Cells(10).ForceNoEdit = True

        If e.Row.Type = RowType.NewRecord Then
            e.Row.Cells(3).ForceNoEdit = True
            e.Row.Cells(4).ForceNoEdit = True
            e.Row.Cells(5).ForceNoEdit = True
            e.Row.Cells(6).ForceNoEdit = True
            e.Row.Cells(7).ForceNoEdit = True
            e.Row.Cells(8).ForceNoEdit = True
        ElseIf e.Row.Type = RowType.Record Then
            e.Row.Cells(3).ForceNoEdit = True
            e.Row.Cells(4).ForceNoEdit = True
            e.Row.Cells(5).ForceNoEdit = True
            e.Row.Cells(6).ForceNoEdit = True
            e.Row.Cells(7).ForceNoEdit = True
            e.Row.Cells(8).ForceNoEdit = True
            Dim dr As DataRowView = DirectCast(e.Row.DataRow, DataRowView)
            Dim code As String = dr("CalculationType").ToString
            Dim comrate As Decimal = dr("CompensateRate")
            Dim el1 As Decimal = dr("Element1")
            Dim el2 As Decimal = dr("Element2")
            Dim el3 As Decimal = dr("Element3")
            If Val(code) = 1 Then
                dr("SumAmountX") = ((comrate / 100) * el1)
                e.Row.Cells(7).Value = ((comrate / 100) * el1)
            ElseIf Val(code) = 2 Then
                dr("SumAmountX") = ((comrate / 100) * el2)
                e.Row.Cells(7).Value = (comrate * el2)
            ElseIf Val(code) = 3 Then
                dr("SumAmountX") = ((comrate / 100) * el3)
                e.Row.Cells(7).Value = ((comrate / 100) * el3)
            End If
            Dim el4 As Decimal
            Try
                el4 = dr("Element4")
            Catch ex As Exception
                el4 = 0
            End Try

            e.Row.Cells(6).Value = el4 * 100

        End If

        If e.Row.Type = RowType.Record Then
            If lockhash(e.Row.Cells(1).Value.ToString.Trim) = True Then
                e.Row.Cells(0).Column.IsRowChecker = False
                e.Row.ForceNoEdit = True
                e.Row.Style.BackColor = Drawing.Color.Gray
            Else
                e.Row.Cells(0).Column.IsRowChecker = True
            End If
        End If
    End Sub



    Protected Sub FundCenterCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles FundCenterCombo.InitializeDataSource
        Dim ds As New DataSet
        'If Session("Versions") > 1 Then
        If IsPostBack = True And Session("Search") = "true" Then
            Dim fctr As String = ""
            fctr = Session("search_fctr")
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If fctr <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & fctr & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
            'Response.Write(sql & "<br />")
        Else
            'ds = PublicFunction.GetChild2(Session("users"))
            'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
            'e.DataSource = ds
            Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
            Dim dt As New BasicData.FCTR_Child2DataTable
            Dim sql = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            sql += " WHERE 1 = 1 "
            sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
            If prefil <> "" Then
                sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
            End If
            sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
            sql += "ORDER BY [Level] ASC, FundCenterCode ASC"
            adap.GetDataByFilter(dt, sql)
            e.DataSource = dt
        End If


        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub ProductCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles ProductCombo.InitializeDataSource

        Dim adapter As New SplitBudgetDSTableAdapters.ProductsTableAdapter

        Dim data As New SplitBudgetDS.ProductsDataTable
        'data = adapter.GetDataByPlanYear(Val(Session("PlanYear")))

        data = adapter.GetDataByF06(PlanYearsTxt.Text)
        e.DataSource = data
    End Sub




    Protected Sub WebGrid1_AddRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        If lockhash(e.Row.Cells(1).Value.ToString.Trim) = True Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถบันทึกได้ เนื่องจากมีการส่งแผนไปแล้ว")
        End If
        Dim adapter As New MSinchuaTableAdapters.BudgetDetailsTableAdapter
        Dim adapter2 As New MSinchuaTableAdapters.ProductItemsTableAdapter
        Dim adapter3 As New MSinchuaTableAdapters.ProductItemRevsTableAdapter
        Dim adapcmmt As New MasterDataSet2TableAdapters.ProductsTableAdapter
        Dim cmmt As String = ""
        cmmt = adapcmmt.GetCmmtF06(e.Row.Cells(2).Value, Val(PlanYearsTxt.Text))
        If cmmt = "" Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถระบุ Commitment Item กรุณาติดต่อผู้ดูแลระบบ")
        End If
        Dim id As Decimal
        'Dim adapter2 As New BasicDataTableAdapters.CmmtDetailsTableAdapter
        'Dim cmmt_id As Decimal = adapter2.GetCmmtId(Val(e.Row.Cells(2).Value))
        'sender.ClientAction.Alert(e.Row.Cells(2).Value)
        Dim count As Integer = adapter.CountDup("F06", e.Row.Cells(1).Value, e.Row.Cells(2).Value, VersionTxt.Text)
        If count > 0 Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถเพิ่มข้อมูลซ้ำได้")
        End If
        'id = adapter.InsertQuery(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, "", "", 0, "", Val(e.Row.Cells(4).Value), Val(e.Row.Cells(5).Value), Val(e.Row.Cells(6).Value), Val(e.Row.Cells(7).Value), 0, 0, 0, 0, 0, Val(e.Row.Cells(8).Value), 0, 0, 0, e.Row.Cells(9).Value, "", "F07", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Date.Now, Date.Now, Session("users"), Session("users"), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, e.Row.Cells(1).Value, Val(PlanYearsTxt.Text), e.Row.Cells(3).Value, Val(PlanYearsTxt.Text), cmmtcode, Val(PlanYearsTxt.Text), Session("users"), Val(e.Row.Cells(2).Value), 1, Val(PlanYearsTxt.Text), 0)
        'id = adapter.InsertQuery(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, "", "", 0, "", Val(e.Row.Cells(4).Value), Val(e.Row.Cells(5).Value), 0, 0, 0, 0, 0, 0, 0, Val(e.Row.Cells(7).Value), 0, 0, 0, e.Row.Cells(8).Value, "", "F07", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Date.Now(), Date.Now, Session("users"), Session("users"), Nothing, Nothing, Nothing, Nothing, e.Row.Cells(2).Value, Val(PlanYearsTxt.Text), e.Row.Cells(1).Value, Val(PlanYearsTxt.Text), Nothing, Nothing, Nothing, Nothing, Session("users"), Nothing, 1, Val(PlanYearsTxt.Text), 0)
        Try
            id = adapter.InsertQuery(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, "", "", 0, "", Val(e.Row.Cells(3).Value), Val(e.Row.Cells(4).Value), Val(e.Row.Cells(5).Value), (Val(e.Row.Cells(6).Value) / 100), 0, 0, 0, 0, 0, Val(e.Row.Cells(8).Value), 0, 0, 0, e.Row.Cells(9).Value, "", "F06", "", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Nothing, Date.Now(), Date.Now, Session("users"), Session("users"), Nothing, Nothing, Nothing, Nothing, e.Row.Cells(2).Value, Val(PlanYearsTxt.Text), e.Row.Cells(1).Value, Val(PlanYearsTxt.Text), Nothing, Nothing, Nothing, Nothing, "1110", Val(PlanYearsTxt.Text), cmmt, Val(PlanYearsTxt.Text))
            logger.Info("User " & Session("users") & " insert product " & e.Row.Cells(2).Value & " of fund center " & e.Row.Cells(1).Value)
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)

            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถเพิ่มข้อมูลได้ กรุณาตรวจสอบจำนวนเงิน")
        End Try

        Dim dr As DataRow = e.Row.DataRow
        dr("Id") = id
        dr("Attachments_amount") = 0
        If WebGrid1.RootTable.Rows.Count Mod 10 = 0 Then
            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        If lockhash(e.Row.Cells(1).Value.ToString.Trim) = True Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถบันทึกได้ เนื่องจากมีการส่งแผนไปแล้ว")
        End If

        Dim adapter As New MSinchuaTableAdapters.BudgetDetailsTableAdapter
        Dim adapter2 As New MSinchuaTableAdapters.ProductItemsTableAdapter
        Dim adapter3 As New MSinchuaTableAdapters.ProductItemRevsTableAdapter
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        Dim id As Decimal
        id = e.Row.KeyValue
        Dim count As Integer = adapter.CountDupUpdate("F06", e.Row.Cells(1).Value, e.Row.Cells(2).Value, id, VersionTxt.Text)
        If count > 0 Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถเพิ่มข้อมูลซ้ำได้")
        End If
        'WebGrid1.ClientAction.Alert(id)
        'Dim adapter2 As New BasicDataTableAdapters.CmmtDetailsTableAdapter
        'Dim cmmt_id As Decimal = adapter2.GetCmmtId(Val(e.Row.Cells(2).Value))
        Dim adapcmmt As New MasterDataSet2TableAdapters.ProductsTableAdapter
        Dim cmmt As String = ""
        cmmt = adapcmmt.GetCmmtF06(e.Row.Cells(2).Value, Val(PlanYearsTxt.Text))
        If cmmt = "" Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถระบุ Commitment Item กรุณาติดต่อผู้ดูแลระบบ")
        End If
        Try
            adapter.UpdateQuery2(Val(e.Row.Cells(3).Value), Val(e.Row.Cells(4).Value), Val(e.Row.Cells(5).Value), (Val(e.Row.Cells(6).Value) / 100), e.Row.Cells(8).Value, e.Row.Cells(9).Value, Date.Now, Session("users"), e.Row.Cells(1).Value, e.Row.Cells(2).Value, cmmt, id)
            adapter12.DeleteBID(id)
            logger.Info("User " & Session("users") & " update product " & e.Row.Cells(2).Value & " of fund center " & e.Row.Cells(1).Value)
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)

            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException("ไม่สามารถแก้ไขข้อมูลได้ กรุณาตรวจสอบจำนวนเงิน")
        End Try


        Dim dr As DataRowView = DirectCast(e.Row.DataRow, DataRowView)
        Dim code As String = dr("CalculationType").ToString
        Dim comrate As Decimal = dr("CompensateRate")
        Dim el1 As Decimal = dr("Element1")
        Dim el2 As Decimal = dr("Element2")
        Dim el3 As Decimal = dr("Element3")
        If Val(code) = 1 Then
            dr("SumAmountX") = (comrate * el1) + el2 + el3
        ElseIf Val(code) = 2 Then
            dr("SumAmountX") = (comrate * el2) + el1 + el3
        ElseIf Val(code) = 3 Then
            dr("SumAmountX") = (comrate * el3) + el1 + el2
        End If
    End Sub

    Sub PlotNode()

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()

        Dim adapter As New FundCenterParentTableAdapters.fctr_viewTableAdapter
        Dim dt As New FundCenterParent.fctr_viewDataTable
        dt = adapter.GetDataByUser(Session("users"), Val(PlanYearsTxt.Text))

        Dim root_id As String

        MyNode.Text = "GSB"
        MyNode.Value = "0"
        root_id = "0"

        If dt.Count > 0 Then

            WebTreeView3.Nodes.Add(MyNode)

            Dim rootpath = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            rootpath = FctrClass.GetRootPrefil(Session("users"), Val(Session("planyear")), prefil)
            Dim rootarr() As String = Split(rootpath, ",")
            WebTreeView3.Nodes.Add(MyNode)

            For i = 0 To rootarr.Length - 1
                PlotChild(rootarr(i), MyNode, 1)
            Next
        End If

    End Sub

    Sub PlotChild(ByVal gpath As String, ByRef cnode As WebTreeViewNode, ByVal level As Decimal)
        'Response.Write(gpath & "<br>")
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Hdatatable = Hadapter.GetDataByGPath(gpath, Val(Session("planyear")))

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()
        For Each row As FundCenterParent.FctHRow In Hdatatable


            MyNode.Text = row.Description
            MyNode.Value = row.FundCenter_FundCenterCode

            cnode.Nodes.Add(MyNode)
        Next

        'Hdatatable = Hadapter.GetDataByUserLikeGpath(gpath & "__", Session("users"), Val(Session("planyear")))
        'For Each row As FundCenterParent.FctHRow In Hdatatable

        '    PlotChild(row.grouppath, MyNode, level + 1)
        'Next

        Dim hadap2 As New FundCenterParentTableAdapters.UserLikeGpathTableAdapter
        Dim hdt2 As New FundCenterParent.UserLikeGpathDataTable
        Dim sql As String = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")

        'If prefil <> "" Then
        '    sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        'End If
        'sql += " AND grouppath like '" & gpath & "__' "
        'sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND Fcth.PlanYear = " & Val(Session("PlanYear"))
        'hadap2.GetDataByFilter(hdt2, sql)

        Dim pathadd As String = "__"
        'For i = 1 To 4
        sql = ""
        Dim fullpath As String = gpath & pathadd
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " AND grouppath like '" & fullpath & "' "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND Fcth.PlanYear = " & Val(Session("PlanYear"))
        hadap2.GetDataByFilter(hdt2, sql)
        'If hdt2.Count > 0 Then
        '    Exit For
        'End If
        'Response.Write(sql & "<br />")
        'pathadd += "__"
        'Next
        For Each row As FundCenterParent.UserLikeGpathRow In hdt2
            If Len(row.grouppath) < 10 Then
                PlotChild(row.grouppath, MyNode, level + 1)
            End If

        Next

    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        GenerateValues()
        If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
            Session.Remove("search_fctr")
            If WebCombo1.Value <> "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
            ElseIf WebCombo1.Value <> "" And WebCombo2.Value = "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users")))
            ElseIf WebCombo1.Value = "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users")))
            Else
                Session.Add("search_fctr", Session("prefilter"))
            End If

        ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
            Session.Remove("search_fctr")
            If WebCombo3.Value = "" Then
                Session.Add("search_fctr", Session("prefilter"))
            Else
                Session.Add("search_fctr", FctrClass.GetSubFundCenter(WebCombo3.Value, Session("users"), Val(PlanYearsTxt.Text), Session("prefilter")))
            End If

        End If
        Session.Remove("Search")
        Session.Add("Search", "true")
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
        FundCenterCombo.ClearCachedDataSource()
        FundCenterCombo.DataBind()
    End Sub

    Sub GenerateValues()
        If hdf1.Value.Length = 0 Then
            Session("Search") = "false"
        End If
        Try
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                ms8.Items.FindByValue(Numx(i).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

    End Sub


    'Protected Sub coppy_btn_Click(sender As Object, e As ImageClickEventArgs) Handles coppy_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.CoppyRow(keyValue)

    '    Next keyValue

    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()

    'End Sub

    'Protected Sub delete_btn_Click(sender As Object, e As ImageClickEventArgs) Handles delete_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.DeleteRow(keyValue)

    '    Next keyValue

    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()
    'End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then
                Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()
                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

                For Each keyValue As String In checkedRows
                    adapter.CoppyRow(keyValue)
                Next keyValue
            Else
                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter
                Dim adapter2 As New fundCenterTableAdapters.AttachmentsTableAdapter
                For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                    Try
                        AttachClass.DeleteSP(keyValue)
                    Catch ex As Exception

                    End Try
                    adapter2.DeleteAttach(keyValue)
                    adapter.DeleteRow(keyValue)

                    logger.Info("User " & Session("users") & " delete key " & keyValue)
                Next keyValue
            End If

            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub WebCombo1_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo1.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt



        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub WebCombo2_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo2.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt


        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub SaveBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SaveBtn.Click
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
    End Sub

    Protected Sub WebGrid1_InitializeColumn(sender As Object, e As ColumnEventArgs) Handles WebGrid1.InitializeColumn
        If e.Column.ColumnType = ColumnType.CheckBox And lockhash.Count > 0 Then
            e.Column.IsRowChecker = False
            e.Column.Width = 24
            e.Column.Caption = " "
        End If
    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource

        Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        Dim dt As New FundCenterParent.SelectorDataTable
        Dim dt2 As New FundCenterParent.SelectorDataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += "ORDER BY Grouppath"
        adap.GetDataByFilter(dt2, sql)
        dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        dt.Merge(dt2)
        'dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        e.DataSource = dt



    End Sub
End Class
